﻿//using System;
//using System.Collections.Generic;
//using System.Globalization;
//using System.Net.Mail;
//using System.Web.Routing;
//using System.Text;

//using Umbraco.Framework.Localization;

//using CreativeMinds.MVC.Common.Abstract;
//using CreativeMinds.MVC.Common.Helpers;

//using mvcForum.Core;
//using mvcForum.Core.Abstractions.Interfaces;
//using mvcForum.Core.Events;
//using mvcForum.Core.Interfaces.AddOns;
//using mvcForum.Core.Interfaces.Data;
//using mvcForum.Core.Interfaces.Events;

//using mvcForum.Web.Extensions;
//using mvcForum.Web.Interfaces;

//namespace mvcForum.AddOns.Subscribe {

//    public class SubscribeAddOn : IAddOn, IAsyncEventListener<NewPostEvent>, IAsyncEventListener<NewTopicEvent> {
//        private readonly IRepository<Post> postRepo;
//        private readonly IRepository<Topic> topicRepo;
//        private readonly ILog logger;
//        private readonly IConfiguration config;
//        private readonly TextManager textManager;
//        private readonly IURLProvider url;
//        private readonly IMailService mail;
//        private readonly IAsyncTask task;
//        private readonly SubscribeConfiguration addOnConfig;

//        public SubscribeAddOn(IRepository<Post> postRepo,
//                                IRepository<Topic> topicRepo,
//                                ILog logger,
//                                IConfiguration config,
//                                TextManager textManager,
//                                IURLProvider url,
//                                IMailService mail,
//                                IAsyncTask task,
//                                SubscribeConfiguration addOnConfig) {

//            this.postRepo = postRepo;
//            this.topicRepo = topicRepo;
//            this.logger = logger;
//            this.config = config;
//            this.textManager = textManager;
//            this.url = url;
//            this.mail = mail;
//            this.task = task;
//            this.addOnConfig = addOnConfig;
//        }

//        #region Queue methods
//        public void Queue(NewTopicEvent payload) {
//            task.Execute(this, payload, this.addOnConfig.Delay);
//        }

//        public void Queue(NewPostEvent payload) {
//            task.Execute(this, payload, this.addOnConfig.Delay);
//        }
//        #endregion

//        #region Handle methods
//        public void Handle(Object payload) {
//            if (payload is NewTopicEvent) {
//                this.Handle((NewTopicEvent)payload);
//            }
//            else if (payload is NewPostEvent) {
//                this.Handle((NewPostEvent)payload);
//            }
//            else {
//                throw new ApplicationException("Unknown payload!");
//            }
//        }

//        public void Handle(NewTopicEvent payload) {
//            Topic topic = this.topicRepo.Read(payload.TopicId);
//            // Iterate the followers.
//            foreach (var ff in topic.Forum.Followers) {
//                // No need to inform the author himself!
//                if (ff.User.Id != topic.Author.Id) {
//                    // Let's create the URL for view topic.
//                    String actionURL = this.url.RouteUrl("ShowForum", new { id = topic.Forum.Id, title = URLHelper.URLFriendlyString(topic.Forum.Name) });
//                    // Get the site's URL from the configuration.
//                    String siteURL = config.SiteURL;
//                    if (siteURL.EndsWith("/")) {
//                        siteURL = siteURL.Substring(0, siteURL.Length - 1);
//                    }
//                    // Merge site URL and view topic URL.
//                    String url = String.Format("{0}{1}", siteURL, actionURL);

//                    this.SendFollowMail(ff.User, "Forum", new { Forum = topic.Forum, Topic = topic }, new { Topic = topic, Forum = topic.Forum, URL = url }, url, topic.Forum.Name);
//                }
//            }
//        }

//        public void Handle(NewPostEvent payload) {
//            Post post = this.postRepo.Read(payload.PostId);
//            // Iterate the followers.
//            foreach (var ft in post.Topic.Followers) {
//                // No need to inform the author himself!
//                if (ft.User.Id != post.Author.Id) {
//                    // Let's create the URL for view topic.
//                    String actionURL = this.url.RouteUrl("ShowTopic", new { id = post.Topic.Id, title = URLHelper.URLFriendlyString(post.Topic.Title) });
//                    // Get the site's URL from the configuration.
//                    String siteURL = config.SiteURL;
//                    if (siteURL.EndsWith("/")) {
//                        siteURL = siteURL.Substring(0, siteURL.Length - 1);
//                    }
//                    // Merge site URL and view topic URL.
//                    String url = String.Format("{0}{1}", siteURL, actionURL);

//                    this.SendFollowMail(ft.User, "Topic", new { Post = post, Topic = post.Topic }, new { Topic = post.Topic, Post = post, URL = url }, url, post.Topic.Title);
//                }
//            }
//        }
//        #endregion

//        private void SendFollowMail(ForumUser recipient, String type, Object subjectValues, Object bodyValues, String url, String title) {
//            // Does the follower have an e-mail address on his account?
//            if (!String.IsNullOrWhiteSpace(recipient.Email)) {
//                logger.Log(EventType.Debug, String.Format("User {0} ({1}) is following {3} {2}.", recipient.Name, recipient.Email, title, type));

//                //
//                // TODO: Put this in a queue?? Do a daily digest! Optional?
//                //

//                // Get the user settings, we'll be localising the text.
//                ForumUserSettings userSettings = recipient.Settings();
//                // Create a LanguageInfo instance that matches the user's settings.
//                LanguageInfo userLI = new LanguageInfo { Culture = new CultureInfo(userSettings.Culture), Key = userSettings.Culture };
//                // Get the subject from the localisation system.
//                String subject = this.textManager.Get<AddOnBuilder>(String.Format("Follow{0}.Subject", type), language: userLI, values: subjectValues);

//                // Let's create the URL for view topic.
//                //String actionURL = this.url.RouteUrl("ShowTopic", new { id = post.Topic.Id, title = URLHelper.URLFriendlyString(post.Topic.Title) });
//                // Get the site's URL from the configuration.
//                //String siteURL = config.SiteURL;
//                //if (siteURL.EndsWith("/")) {
//                //	siteURL = siteURL.Substring(0, siteURL.Length - 1);
//                //}
//                // Merge site URL and view topic URL.
//                //String url = String.Format("{0}{1}", siteURL, actionURL);

//                // Get the content of the body from the localisation system!
//                String body = this.textManager.Get<AddOnBuilder>(String.Format("Follow{0}.Body", type), language: userLI, values: bodyValues);

//                try {
//                    // Send the message.
//                    this.mail.Send(new MailAddress(config.RobotEmailAddress, config.RobotName), new List<MailAddress> { { new MailAddress(recipient.Email) } }, subject, body);

//                    logger.Log(EventType.Debug, String.Format("The message to user {0} ({1}) has been sent.", recipient.Name, recipient.Email));
//                }
//                catch (Exception ex) {
//                    logger.Log(EventType.Error, String.Format("Could not send e-mail to {0}, MessageAdded", recipient.Email), ex);
//                }
//            }
//        }

//        public Byte Priority {
//            get {
//                return (Byte)EventPriority.Lowest;
//            }
//        }

//        public Boolean RunAsynchronously {
//            get {
//                return this.addOnConfig.RunAsynchronously;
//            }
//        }
//    }
//}